//
// Created by leisurexi on 11/29/20.
// echo_server.c
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/socket.h>

#define BUF_SIZE 1024

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int server_sock, client_sock;
    char message[BUF_SIZE];
    int str_len, i;

    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len;

    if (argc != 2) {
        printf("Usage : %s <port>\n", argv[0]);
        exit(0);
    }

    server_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (server_sock == -1)
        error_handling("socket() error");

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(atoi(argv[1]));

    int on = 1;
    setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    if (bind(server_sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1)
        error_handling("bind() error");

    if (listen(server_sock, 5) == -1)
        error_handling("listen() error");

    client_addr_len = sizeof(client_addr);
    for (i = 0; i < 5; i++) {
        client_sock = accept(server_sock, (struct sockaddr *) &client_addr, &client_addr_len);
        if (client_sock == -1)
            error_handling("accept() error");
        else
            printf("Connected client %d \n", i + 1);

        while ((str_len = read(client_sock, message, BUF_SIZE)) != 0)
            write(client_sock, message, str_len);

        close(client_sock);
    }

    close(server_sock);
    return 0;
}